<template>
  <!-- 物资分类管理 -->
  <el-button type="success" @click="handleOpenInsertDialog()">新增分类</el-button>

  <!-- 树形表格展示 -->
  <el-table :data="tableData" :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
    row-key="material_Category_Id" default-expand-all>
    <el-table-column type="index" width="50" label="序号" />
    <el-table-column prop="material_Category_Name" label="分类名称" />
    <el-table-column label="操作" width="250">
      <template #default="scope">
        <el-button type="success" size="small" link @click="handleOpenEditDialog(scope.row)">编辑</el-button>
        <el-button type="warning" size="small" link @click="handleOpenEditDialog(scope.row)">查看</el-button>
        <el-button type="danger" size="small" link @click="handleDeleteCategory(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增分类对话框 -->
  <el-dialog v-model="dialogVisible" title="新增物资类型" width="500">
    <el-form :model="categoryForm" style="width: 400px">
      <el-form-item label="分类名称">
        <el-input v-model="categoryForm.material_Category_Name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="父级分类">
        <el-cascader style="width: 400px" v-model="categoryForm.selectedParentIds" :options="categoryOptions"
          :props="cascaderProps" placeholder="顶级" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateCategory">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑分类对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑物资类型" width="500">
    <el-form :model="editForm" style="width: 400px">
      <el-form-item label="分类名称">
        <el-input v-model="editForm.material_Category_Name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="父级分类">
        <el-cascader style="width: 400px" v-model="editForm.selectedParentIds" :options="categoryOptions"
          :props="cascaderProps" placeholder="顶级" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateCategory">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { supplies, suppliesAdd, suppliesDel, suppliesshow } from '@/api/Index'
// 对话框显示状态
const dialogVisible = ref(false) // 新增对话框
const editDialogVisible = ref(false) // 编辑对话框

// 分类表单数据
const categoryForm = reactive({
  material_Category_Name: '',
  selectedParentIds: [] as number[] // 选择的父级路径ID数组
})

// 编辑表单数据
const editForm = reactive({
  material_Category_Id: 0, // 分类 ID
  material_Category_Name: '', // 分类名称
  selectedParentIds: [] as number[] // 选择的父级路径ID数组
})

// 级联选择器配置
const cascaderProps = {
  checkStrictly: true, // 允许选择任意层级
  label: 'material_Category_Name', // 显示文本字段
  value: 'material_Category_Id', // 值字段
  children: 'childrens' // 子节点字段
}

// 分类树数据（表格&级联选择器共用）
const categoryOptions = ref<CategoryTree[]>([])
const tableData = ref<CategoryTree[]>([]) // 表格数据

interface CategoryTree {
  material_Category_Id: number
  material_Category_Name: string
  parent_Id: number
  childrens?: CategoryTree[]
}

/**
 * 获取分类树数据
 */
const fetchCategoryTree = async () => {

  supplies().then(res => {
    categoryOptions.value = res.data
    tableData.value = res.data
  })

}


//  打开新增对话框

const handleOpenInsertDialog = () => {
  dialogVisible.value = true
}

/**
 * 创建新分类
 */
const handleCreateCategory = async () => {
  try {
    // 获取父级ID（选中路径的最后一个ID）
    const parent_Id = categoryForm.selectedParentIds.length > 0
      ? categoryForm.selectedParentIds[categoryForm.selectedParentIds.length - 1]
      : 0
    const data = ref({
      material_Category_Name: categoryForm.material_Category_Name,
      parent_Id: parent_Id
    })
    suppliesAdd(data.value).then(res => {
      if (res.isSuc) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        resetForm()
        fetchCategoryTree() // 刷新数据
      } else {
        ElMessage.error(res.data.message)
      }
    })


  } catch (error) {
    ElMessage.error('请求失败')
  }
}

/**
 * 打开编辑对话框
 */
const handleOpenEditDialog = (row: CategoryTree) => {
  // 填充编辑表单数据
  editForm.material_Category_Id = row.material_Category_Id
  editForm.material_Category_Name = row.material_Category_Name
  editForm.selectedParentIds = getParentPath(row.material_Category_Id) // 获取父级路径
  editDialogVisible.value = true
}

/**
 * 更新分类
 */
const handleUpdateCategory = async () => {
  try {
    // 获取父级ID（选中路径的最后一个ID）
    const parent_Id = editForm.selectedParentIds.length > 0
      ? editForm.selectedParentIds[editForm.selectedParentIds.length - 1]
      : 0
    const from = ref({
      material_Category_Id: editForm.material_Category_Id,
      material_Category_Name: editForm.material_Category_Name,
      parent_Id: parent_Id
    })
    suppliesDel(from.value).then(res => {
      if (res.isSuc) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        fetchCategoryTree() // 刷新数据
      } else {
        ElMessage.error(res.data.message)
      }
    })

  } catch (error) {
    ElMessage.error('请求失败')
  }
}

/**
 * 删除分类
 */
const handleDeleteCategory = async (row: CategoryTree) => {
  try {
    // 确认删除
    await ElMessageBox.confirm('确定删除该分类吗？', '提示', {
      type: 'warning'
    })
    const from = ref({
      material_Category_Id: row.material_Category_Id
    })
    suppliesshow(from.value).then(async res => {
      if (res.isSuc) {
        ElMessage.success('删除成功')
        await fetchCategoryTree() // 刷新数据
      } else {
        ElMessage.error(res.message)
      }
    })

  } catch (error) {
    ElMessage.error('取消删除或请求失败')
  }
}

/**
 * 获取父级路径
 */
const getParentPath = (categoryId: number): number[] => {
  const findPath = (data: CategoryTree[], targetId: number, path: number[] = []): number[] | null => {
    for (const item of data) {
      if (item.material_Category_Id === targetId) {
        return path
      }
      if (item.childrens && item.childrens.length > 0) {
        const result = findPath(item.childrens, targetId, [...path, item.material_Category_Id])
        if (result) return result
      }
    }
    return null
  }
  return findPath(categoryOptions.value, categoryId) || []
}

/**
 * 重置表单
 */
const resetForm = () => {
  categoryForm.material_Category_Name = ''
  categoryForm.selectedParentIds = []
}

// 初始化加载数据
onMounted(() => {
  fetchCategoryTree()
})
</script>